<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Rooms extends Backend
{


    protected $noNeedLogin = ['getRoomInfo'];
    // 无需鉴权的接口,*表示全部

    /**
     * House模型对象
     * @var \app\admin\model\House
     */
    protected $model = null;
    protected $hid = null;
    protected $adminId = null;
    protected $relationSearch = true; //开启关联查询

    public function _initialize()
    {
        parent::_initialize();

        $this->hid = Session::get("admin")["hotelid"];
        $this->adminId = Session::get("admin")["id"];

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {


        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $this->relationSearch = true; // 解决排序问题
        if ($this->request->isAjax()) {

            $model = model('House');
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //实现关联查询的关键是 要在对应的主表里添加  多个条件 逗号分割 ，注意是关联字段 这里是 choice 是因为对应的model 里 对外输出的是 choice
            list($where, $sort, $order, $offset, $limit) = $this->buildparams("fa_house.id,fa_house.h_title,choice.h_title");

            if($this->adminId == 1){
                $total = $model
                    ->with(['choice'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $list = $model
                    ->with(['choice'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            }else{
                $total = $model
                    ->with(['choice'])
                    ->where($where)
                    ->where("h_id" ,'in',$this->hid)
                    ->order($sort, $order)
                    ->count();
                $list = $model
                    ->with(['choice'])
                    ->where($where)
                    ->where("h_id" ,'in',$this->hid)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);

        }
        return $this->view->fetch();
    }


    /**
     * 查看
     */
    public function indexold()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            $search = $this->request->request("search");
            $search = trim($search);
            $model = model('House');


            //快速搜索 根据 id title 搜索
            /*    list($where, $sort, $order, $offset, $limit) = $this->buildparams("id,title");
                $total = $this->model
                    ->where($mimetypeQuery)
                    ->where($where)
                    ->order($sort, $order)
                    ->count();*/


            list($where, $sort, $order, $offset, $limit) = $this->buildparams("htitle");

            $total = $model->where('fa_house.h_title','like','%'.$search.'%')->order($sort, $order)->count();

            $list = $model
                ->join("hotels h",'fa_house.h_id = h.id')
                ->field("fa_house.*,h.h_title as htitle,h.h_unit")
                ->where('fa_house.h_title','like','%'.$search.'%')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);


        }
        return $this->view->fetch();
    }


    /*
    * 添加酒店
    */

     public function add(){


             $serviceList = [];
             if ($this->request->isPost()) {
                 $model = model('house');
                 $params = $this->request->post();

                 if ($params) {
                     $params = $this->preExcludeFields($params);


                     if(!empty($params["row"]["h_imgs"])){
                         $imgs = explode(",",$params["row"]["h_imgs"]);
                         $params["row"]["h_img"] = $imgs[0];
                     }


                     if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                         $params[$this->dataLimitField] = $this->auth->id;
                     }


                     //房间设施
                     $serv = $params["h_servs"];
                     if($serv[0] != ""){
                         $serarr = implode(",",$serv);
                         $params["row"]["h_servs"] = $serarr;
                     }

                     //基础设施
                     $service = $params["h_service"];
                     if($service[0] != ""){
                         $serarr = implode(",",$service);
                         $params["row"]["h_service"] = $serarr;
                     }
                     //卫浴设施
                     $service2 = $params["h_service2"];
                     if($service2[0] != ""){
                         $serarr2 = implode(",",$service2);
                         $params["row"]["h_service2"] = $serarr2;
                     }

                     //入住须知
                     $h_read = $params["h_read"];
                     if($h_read[0] != ""){
                         $h_reads = implode(",",$h_read);
                         $params["row"]["h_read"] = $h_reads;
                     }

                     $result = false;
                     Db::startTrans();

                     try {

                         $result = $model->save($params["row"]);


                         Db::commit();
                     } catch (ValidateException $e) {
                         Db::rollback();
                         $this->error($e->getMessage());
                     } catch (PDOException $e) {
                         Db::rollback();
                         $this->error($e->getMessage());
                     } catch (Exception $e) {
                         Db::rollback();
                         $this->error($e->getMessage());
                     }
                     if ($result !== false) {
                         $this->success();
                     } else {
                         $this->error(__('No rows were inserted'));
                     }
                 }
                 $this->error(__('Parameter %s can not be empty', ''));
             }else{

                 //获取酒店列表
                 $model = model('Hotels');
                 if($this->adminId == 1){
                     $hotelList = $model->where("h_status='normal'")->field("hid,h_title")->select();
                     //获取第一个酒店id
                     $hotelnum = $model->where("h_status='normal'")->value("h_storey");
                 }else{
                     $hotelList = $model->where("h_status='normal'")->where('hid','in',$this->hid)->field("hid,h_title")->select();
                     //获取第一个酒店id
                     $hotelnum = $model->where("h_status='normal'")->where('hid','in',$this->hid)->value("h_storey");
                 }


                 $hotelNumArr = $this->reNum($hotelnum);


                 //获取房间设施
                 $cate = db('category');
                 $res = $cate->where("type='房间属性' and status='normal' ")->field("id,name")->select();
                 if($res){
                     $serviceList = $res;
                 }else{
                     $serviceList = [];
                 }

                 $this->assign("serviceList",$serviceList);
                 $this->assign("hotelNumArr",$hotelNumArr);
                 $this->assign("hotelList",$hotelList);
                 return $this->view->fetch();
            }
     }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {


        $model = model('house');
        $row = $model->get($ids)->toArray();

        $this->assign('ids',$ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);

                try {

                    if(!empty($params["row"]["h_imgs"])){
                        $imgs = explode(",",$params["row"]["h_imgs"]);
                        $params["row"]["h_img"] = $imgs[0];
                    }


                    if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                        $params[$this->dataLimitField] = $this->auth->id;
                    }

                    //房间设施
                    $serv = $params["h_servs"];
                    if($serv[0] != ""){
                        $serarr = implode(",",$serv);
                        $params["row"]["h_servs"] = $serarr;
                    }

                    //基础设施
                    $service = $params["h_service"];
                    if($service[0] != ""){
                        $serarr = implode(",",$service);
                        $params["row"]["h_service"] = $serarr;
                    }
                    //卫浴设施
                    $service2 = $params["h_service2"];
                    if($service2[0] != ""){
                        $serarr2 = implode(",",$service2);
                        $params["row"]["h_service2"] = $serarr2;
                    }

                    //入住须知
                    $h_read = $params["h_read"];
                    if($h_read[0] != ""){
                        $h_reads = implode(",",$h_read);
                        $params["row"]["h_read"] = $h_reads;
                    }

                    $result = $model->where("id=$ids")->update($params["row"]);


                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            //获取酒店列表
            $model = model('Hotels');

            if($this->adminId == 1){
                $hotelList = $model->where("h_status='normal'")->field("hid,h_title")->select();

            }else{
                $hotelList = $model->where("h_status='normal'")->where('hid','in',$this->hid)->field("hid,h_title")->select();

            }


            $hotelnum = $model->where("h_status='normal'")->where("hid={$row['h_id']}")->value("h_storey");
            $hotelNumArr = $this->reNum($hotelnum);
            //获取房间设施
            $cate = db('category');
            $res = $cate->where("type='房间属性' and status='normal' ")->field("id,name")->select();
            if($res){
                $serviceList = $res;
            }else{
                $serviceList = [];
            }

            $this->assign("serviceList",$serviceList);

            $this->assign("hotelNumArr",$hotelNumArr);
            $this->assign("hotelList",$hotelList);
        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {


        if ($ids) {
            $model = model('house');
            $list = $model->where("id", 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



    /**
     * 批量更新
     */
    public function multi($ids = "")
    {

        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $model = model('house');
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {

                    if(key_exists('h_status',$values)){
                        //动态改变房态h_statusText 状态
                        $values["h_statusText"] = $values["h_status"];
                    }

                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $model->where("id", 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //获取房间数据 右侧
    public function getRoomInfo(){

        $id = $this->request->param("id");
        $model = model('house');
        $info = $model
            ->join("hotels h",'fa_house.h_id = h.hid')
            ->field("fa_house.id,fa_house.beforeTime,h_id,fa_house.h_housebrand,fa_house.h_storey,fa_house.h_title,h_statusText,h_price,h_allprice,h.h_title as htitle,h.h_storey as hstorey,h.h_unit")
            ->where("fa_house.id={$id}")
            ->find()->toArray();

        if($info["beforeTime"]){
            $info["beforeTime"] = date("Y-m-d H:i:s",$info["beforeTime"]);
        }else{
            $info["beforeTime"] = "无预约限制";
        }

        //获取入住信息
        $moveInfo = db("order")->where(["room_id"=>$id,'pay_status'=>2])
            ->join("user","fa_order.user_id = user.id")
            ->field("user.nickName,order_number,user_id,price,ballprice,all_price,deposit,all_money,hour,pay_time,pay_status,stime,etime,return_money,refund_status,add_time,moveinto_time,checkout_time")
            ->order("pay_status desc,fa_order.id desc")
            ->find();

        if($moveInfo){
            $moveInfo["add_time"] = date("Y-m-d H:i:s",$moveInfo["add_time"]);
            $moveInfo["moveinto_time"] = date("m-d号 H:i",$moveInfo["moveinto_time"]);
            $moveInfo["etime"] = date("m-d号 H:i",$moveInfo["etime"]);
            $moveInfo["stime"] = date("m-d号 H:i",$moveInfo["stime"]);
        }


        //获取预约信息
        $list = db("order")->where(["room_id"=>$id,'pay_status'=>1])
            ->join("user","fa_order.user_id = user.id")
            ->field("user.nickName,order_number,user_id,price,ballprice,all_price,deposit,all_money,hour,pay_time,pay_status,stime,etime,return_money,refund_status,add_time,moveinto_time,checkout_time")
            ->order("pay_status desc,fa_order.id desc")
            ->select();

        foreach ($list as &$vv){
            $vv["add_time"] = date("Y-m-d H:i:s",$vv["add_time"]);
            $vv["moveinto_time"] = date("m-d号 H:i",$vv["moveinto_time"]);
            $vv["etime"] = date("m-d号 H:i",$vv["etime"]);
            $vv["stime"] = date("m-d号 H:i",$vv["stime"]);
        }


        if($info){
            if($moveInfo){
                $info["moveInfo"] = $moveInfo;
            }else{
                $info["moveInfo"] = "";
            }
            if($list){
                $info["reserveList"] = $list;
            }else{
                $info["reserveList"] = [];
            }
            $this->success("success","",$info);
        }else{
            $this->error("error");
        }

    }

    //修改房间状态 比如 改为入住 那对应的订单入住时间也有写入时间 订单管理改变订单入住也重新写入 入住时间
    public function changeRoomStatus(){

        $id = $this->request->param("id");
        $statusText = $this->request->param("statusText");
        $order_number = $this->request->param("order_number");

        $model = model('house');
        $data["h_statusText"] = $statusText;
        if($statusText == "hidden"){
            $data["h_status"] = $statusText;
        }

        //目前只考虑 用户 从 预定到入住（使用的情况），入住时间写入 是否考虑实时写入 这里先只改变订单为 已支付(入住)
        if($statusText == "using"){
            //db("order")->where(["order_number"=>$order_number])->update(["moveinto_time"=>time()]);
            db("order")->where(["order_number"=>$order_number])->update(["pay_status"=>2]);
        }

        //如果房源由预定变更为空闲,需要判断订单里是否有未结束的订单：比如订单里是否有用预定且预定时间在预定时间两小时内 根据预定时间的创建时间来计算 两小时 ；而不是入住时间
        //如果存在提示不可以修改为任何空闲状态，可以修改成其状态，比如维系 打扫等，定时任务会根据时间自动将两小时内的预定房间 切换为 预定状态
        //如果订单已经超过了结束时间 后台可以改变状态
        if($statusText == "normal"){
            $time = time();
            $time = $time + 7200;
            $olist = db("order")->where("room_id={$id}")->where("add_time < {$time}")->where("pay_status=1")->find();
            if($olist){
                $this->error("该房间在接下来的两个小时内已被预定，不可以修改为空闲状态,修改为入住状态后，可继续操作");
            }
        }

        $effect = $model->where("id={$id}")->update($data);
        if($effect){
            $this->success("状态修改成功","",$effect);
        }else{
            $this->error("状态修改失败");
        }

    }

    //批量设置房间单价 和 房间封顶价
    public function setprice(){
        if ($this->request->isGet()) {
            $params = $this->request->get()["ids"];
            $this->assign("ids",$params);
            return $this->view->fetch();
        }

    }

    //批量设置房间单价 和 房间封顶价
    public function dosetprice(){
        if ($this->request->isPost()) {
            $params = $this->request->post();

           $ids = $params["h_ids"];
           $data = $params["row"];

            $model = model('house');
            $effect = $model->where("id", 'in', $ids)->update($data);
            if($effect){
                $this->success();
            }else{
                $this->error("设置错误");
            }

        }

    }

    //动态返回酒店楼层数
    public function AjaxHotelNum(){
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $id = $params["hotelid"];
            //获取第一个酒店id
            $model = model('Hotels');
            $hotelnum = $model->where("id={$id}")->value("h_storey");
            if($hotelnum < 1 ){
                $this->error("error");
            }else{
                $hotelNumArr = $this->reNum($hotelnum);
                $this->success("success","",$hotelNumArr);
            }


        }
    }

     //返回楼层号数组
    public function reNum($id){
        $index = array();
        if($id == 1){
            array_push($index,1);
        }else{
            for ($i = 1;$i<=$id;$i++){
                array_push($index,$i);
            }
        }

        return $index;
    }




}
